package com.mpyy.handler.sales;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mpyy.pojo.*;
import com.mpyy.service.sales.ReturnedPurchaseServiceInter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

/**
 * @version 1.0
 * @Description ReturnedPurchaseDaoInter
 * @Author YYJC
 * @Date 2022-03-07 9:03
 */
@RestController
public class ReturnedPurchaseController {
    @Autowired
    @Qualifier(value = "returnedPurchaseService")
    private ReturnedPurchaseServiceInter returnedPurchaseServiceInter;

    /**
     * 查询商品清单
     * @return
     */
    @RequestMapping(value = "/showReturnedPurchase")
    public String searchReturnedPurchase(SaleOrderDesc saleOrderDesc, String custId, String salOrdId){
        /*客户表*/
        CustomerInfo customerInfo = new CustomerInfo ();
        /*给客户表赋值*/
        customerInfo.setCustId (custId);
        /*通过商品表给客户表赋值*/
        saleOrderDesc.setCustomerInfo (customerInfo);

        /*销售订单表*/
        SaleOrder saleOrder = new SaleOrder ();
        /*给销售订单表赋值*/
        saleOrder.setSalOrdId (salOrdId);
        /*通过商品表给销售订单表赋值*/
        saleOrderDesc.setSaleOrder (saleOrder);

        List<SaleOrderDesc> saleOrderDescs = returnedPurchaseServiceInter.searchReturnedPurchase (saleOrderDesc);

        HashMap<String,Object> productInfoMap = new HashMap<> ();
        productInfoMap.put ("code",0);
        productInfoMap.put ("msg","");
        productInfoMap.put ("count",saleOrderDescs.size ());
        productInfoMap.put ("data",saleOrderDescs);

        return JSON.toJSONString (productInfoMap);
    }

    /**
     * 仓库下拉框
     * @param response
     * @param request
     * @throws IOException
     */
    @RequestMapping(value = "/showStorehouse")
    public void searchStorehouse(HttpServletResponse response, HttpServletRequest request) throws IOException {
        List<DepotInfo> depotInfos = returnedPurchaseServiceInter.searchStorehouse();

        request.setCharacterEncoding("utf-8");  //防止乱码
        response.setContentType("text/html;charset=utf-8");
        response.setHeader("Cache-Control", "no-cache");

        /*开启流*/
        PrintWriter writer = response.getWriter ();
        /*改为json格式*/
        writer.print (JSON.toJSONString (depotInfos));
        /*关闭流*/
        writer.close ();

    }

    /**
     * 查询商品批次信息
     * @param productId
     * @return
     */
    @RequestMapping(value = "/showCommodityBatch/{productId}/{salOrdId}")
    public String searchCommodityBatch(@PathVariable("productId") String productId ,@PathVariable("salOrdId") String salOrdId){
        SaleOrderDesc saleOrderDesc = new SaleOrderDesc ();
        saleOrderDesc.setProductId (productId);
        saleOrderDesc.setSalOrdId (salOrdId);
        List<SaleOrderDesc> saleOrderDescs = returnedPurchaseServiceInter.searchCommodityBatch (saleOrderDesc);

        HashMap<String,Object> saleOrderDescMap = new HashMap<> ();
        saleOrderDescMap.put ("code",0);
        saleOrderDescMap.put ("msg","");
        saleOrderDescMap.put ("count",saleOrderDescs.size ());
        saleOrderDescMap.put ("data",saleOrderDescs);
        return JSON.toJSONString (saleOrderDescMap);
    }


    /**
     * 客户与客户类型
     * @return
     */
    @RequestMapping(value = "/showCustomerInfo")
    public String searchCustomerInfo(CustomerInfo customerInfo){
        List<CustomerInfo> customerInfos = returnedPurchaseServiceInter.searchCustomerInfo (customerInfo);


        HashMap<String,Object> customerInfoMap = new HashMap<> ();
        customerInfoMap.put ("code",0);
        customerInfoMap.put ("msg","");
        customerInfoMap.put ("count",customerInfos.size ());
        customerInfoMap.put ("data",customerInfos);
        return JSON.toJSONString (customerInfoMap);
    }

    /**
     * 查询经办人
     * @return
     */
    @RequestMapping(value = "/showEmpName")
    public String searchEmpName() {
        List<EmployeeInfo> employeeInfos = returnedPurchaseServiceInter.searchEmpName ( );

        HashMap<String,Object> employeeInfoMap = new HashMap<> ();
        employeeInfoMap.put ("code",0);
        employeeInfoMap.put ("msg","");
        employeeInfoMap.put ("count",employeeInfos.size ());
        employeeInfoMap.put ("data",employeeInfos);
        return JSON.toJSONString (employeeInfoMap);
    }


    /**
     * 新增数据至销售退货
     * @param proSaleReturn
     * @param proSaleReturnDesc
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/addSalesReturn/{proSaleReturn}/{proSaleReturnDesc}")
    public String updateSalesReturn(@PathVariable("proSaleReturn") String proSaleReturn ,@PathVariable("proSaleReturnDesc") String proSaleReturnDesc) throws Exception {
        /*实例化退货表对象*/
        SaleReturn saleReturn = new SaleReturn ();
        /*获取页面传递过来的销售退货数据，并转成pojo对象*/
        JSONObject o = JSONObject.parseObject(proSaleReturn);
        /*将值赋给对应的属性*/
        /*销售退货编号*/
        saleReturn.setSalRetId (o.getString ("salRetId"));
        /*销售退货日期*/
        saleReturn.setSalRetDate (o.getDate ("salRetDate"));
        /*客户编号*/
        saleReturn.setCustId (o.getString ("custId"));
        /*仓库编号*/
        saleReturn.setDepotId (o.getString ("depotId"));
        /*员工编号*/
        saleReturn.setEmpId (o.getString ("empId"));
        /*实退金额*/
        saleReturn.setSalRetRealRefund (o.getDouble ("salRetRealRefund"));
        /*备注*/
        saleReturn.setSalRetComment (o.getString ("salRetComment"));
        /*应退金额*/
        saleReturn.setSalRetRefunded (o.getDouble ("salRetRefunded"));

        //实例化一个销售退货明细对象
        SaleReturnDesc saleReturnDesc = new SaleReturnDesc ();
        //创建一个StringBuffer对象，获取页面传递过来的销售退货明细数据，拼接还原后加入StringBuffer中
        StringBuffer stringBuffer = new StringBuffer();
        stringBuffer.append("[" + proSaleReturnDesc + "]");

        /*List<Map<String , Object>> mapList = (List<Map<String, Object>>) JSONArray.parse(stringBuffer.toString());
        for (Map<String, Object> stringObjectMap : mapList) {
            for (String s : stringObjectMap.keySet()) {
                System.out.println(s);
            }
        }*/

        //调用自定义的转换工具类
        List<SaleReturnDesc> saleReturnDescs = ProSalesUtil.decomposeJsonArray(stringBuffer, SaleReturnDesc.class);
        /*for (int i = 0;i<saleReturnDescs.size ();i++){
            System.out.println (saleReturnDescs.get (i));
        }*/

        //调用新增商品销售信息的方法
        Integer b = returnedPurchaseServiceInter.updateSalesReturn (saleReturn,saleReturnDescs);

        return JSON.toJSONString (b);
    }


    /**
     * 原始单号
     * @param custId
     * @return
     */
    @RequestMapping(value = "/showSaleCustId/{custId}")
    public String searchSaleCustId(@PathVariable("custId") String custId){
        /*从页面中获取客户ID*/
        SaleOrder saleOrder = new SaleOrder ();
        saleOrder.setCustId (custId);

        /*查询对应销售订单号*/
        List<SaleOrder> saleOrders = returnedPurchaseServiceInter.searchSaleCustId (saleOrder);

        HashMap<String,Object> saleOrderMap = new HashMap<> ();
        saleOrderMap.put ("code",0);
        saleOrderMap.put ("msg","");
        saleOrderMap.put ("count",saleOrders.size ());
        saleOrderMap.put ("data",saleOrders);
        return JSON.toJSONString (saleOrderMap);

    }


    /**
     * 左侧类别
     * @return
     */
    @RequestMapping(value = "/showReturnInfo", produces = "text/html;charset=utf-8")
    public String searchReturnInfo(){
        /*调用查询方法*/
        List<ProductType> productTypes = returnedPurchaseServiceInter.searchReturnInfo ( );

        //迭代循环删除商品信息为空的级别
        List<ProductType> children = productTypes.get(0).getChildren();
        Iterator<ProductType> iterator = children.iterator();
        while (iterator.hasNext()){
            ProductType commodityType = iterator.next();
            if (commodityType.getChildren().size() == 0) {
                iterator.remove();
            }
        }
        /*转为的格式*/
        String treeData = JSON.toJSONString(productTypes).replaceAll("proTypeId","id").replaceAll("proLevelParId","parentId").replaceAll("proTypeName","title");
        return treeData;
    }


    /**
     * 顾客退货树状图
     * @return
     */
    @RequestMapping(value = "/showReturnTree/{proTypeId}")
    public String searchReturnTree(@PathVariable String proTypeId){
        /*调用查询方法*/
        List<SaleOrderDesc> saleOrderDescs = returnedPurchaseServiceInter.searchReturnTree (proTypeId);

        HashMap<String,Object> saleOrderDescMap = new HashMap<> ();
        saleOrderDescMap.put ("code",0);
        saleOrderDescMap.put ("msg","");
        saleOrderDescMap.put ("data",saleOrderDescs);

        /*System.out.println (saleOrderDescs);*/

        return JSON.toJSONString (saleOrderDescMap);
    }

    /**
     * 顾客退货历史
     * @param productId
     * @param salRetDescOriginalNum
     * @return
     */
    @RequestMapping(value = "/showReturnHistory/{productId}/{salRetDescOriginalNum}")
    public String searchReturnHistory(@PathVariable String productId,@PathVariable String salRetDescOriginalNum){
        /*创建退货明细对象*/
        SaleReturnDesc saleReturnDesc = new SaleReturnDesc ();
        /*赋值*/
        saleReturnDesc.setProductId (productId);
        saleReturnDesc.setSalRetDescOriginalNum (salRetDescOriginalNum);
        System.out.println (saleReturnDesc);

        /*调用查询方法*/
        List<SaleReturn> saleReturns = returnedPurchaseServiceInter.searchReturnHistory (saleReturnDesc);
        System.out.println (saleReturns);

        HashMap<String,Object> saleReturnDescMap = new HashMap<> ();
        saleReturnDescMap.put ("code",0);
        saleReturnDescMap.put ("msg","");
        saleReturnDescMap.put ("data",saleReturns);

        return JSON.toJSONString (saleReturnDescMap);
    }

}